package com.nx.platform.es.biz.esspider.handler;

import com.google.common.base.Enums;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreMaps;
import com.nx.platform.es.common.utils.ComplexParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @since 2017年3月27日
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleParamsConvertHandler extends AbstractSimpleHandler {

    private static final Logger LOGGER = LogManager.getLogger(SimpleParamsConvertHandler.class);

    private String field;
    private ComplexParser type;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        field = MoreMaps.getString(settings, "field", "params");
        type = Enums.getIfPresent(ComplexParser.class, MoreMaps.getString(settings, "type", "PARAM")).or(ComplexParser.PARAM);
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.values().forEach((Item item) ->
                item.getDoc().put(field, convertParams(item.getDoc().remove(field)))
        );
    }

    private Map<String, List<Long>> convertParams(Object object) {
        if (object instanceof String) {
            try {
                return type.parse(String.valueOf(object));
            } catch (Throwable e) {
                LOGGER.warn("convert params error: {}", object, e);
            }
        }
        return new LinkedHashMap<>(0);
    }
}
